package com.wk.hooker.hooks;

import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.Layout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.PopupWindow;

import com.wk.hooker.MainActivity;
import com.wk.hooker.login.R;
import com.wk.hooker.util.RefreshLoginActivity;

import java.util.List;

/**
 * Created by wuchu on 16/4/10.
 */
public class Hookservice extends Service {


    private  Notification notification;

    private Bitmap largbitmap;


    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    if (!isRunningApp(getApplicationContext(), "com.tencent.mm")) {
                        Intent intent = getPackageManager().getLaunchIntentForPackage("com.tencent.mm");
                        startActivity(intent);
                        getBaseContext().startActivity(intent);
                    } else {
                        Intent intent = new Intent(getBaseContext(), RefreshLoginActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                        getBaseContext().startActivity(intent);
                    }
                    break;
                case 1:
//                    if (daemonthread == null || !daemonthread.isAlive()) {
//                       // startDaemonethread();
//                    }
//                    NotificationManager nm1 = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//                    notification.icon=R.mipmap.ic_launcher;
//                    nm1.notify(1,notification);
                    break;
                case 3:
                    HookThread hookThread = HookThread.getIntance();
                    hookThread.stopHookService();

                    hookThread = HookThread.getIntance();
                    hookThread.setHandler(handler);
                    hookThread.setContext(getBaseContext());
                    hookThread.startHookService();
                    if (!hookThread.isAlive()) {
                        hookThread.start();
                        Log.v("WC", " 开启线程服务");
                    }
                    break;
            }
        }
    };


    /**
     * ******
     * 守护线程
     */
    private Thread daemonthread;
    private boolean isdaemonthread = true;


    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    @Override
    public void onCreate() {
        super.onCreate();


    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        largbitmap = BitmapFactory.decodeResource(getApplicationContext().getResources(),R.mipmap.ic_launcher_web);
        notification = new Notification(R.mipmap.ic_launcher_web, getText(R.string.app_name_version),
                System.currentTimeMillis());
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        notification.setLatestEventInfo(this, getText(R.string.app_name_version),
                "服务前台运行避免被杀死", pendingIntent);
        startForeground(1, notification);

        HookThread hookThread = HookThread.getIntance();
        hookThread.setHandler(handler);
        hookThread.setContext(getBaseContext());
        hookThread.startHookService();
        if (!hookThread.isAlive()) {
            hookThread.start();
            Log.v("WC", " 开启线程服务");
        }
        hookThread.setUncaughtExceptionHandler(uncaughtExceptionHandler);
       // startDaemonethread();
        return super.onStartCommand(intent,START_REDELIVER_INTENT,startId);
    }


    private Thread.UncaughtExceptionHandler uncaughtExceptionHandler = new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread thread, Throwable throwable) {
            HookThread hookThread = HookThread.getIntance();
            hookThread.stopHookService();
            hookThread = HookThread.getIntance();
            hookThread.setHandler(handler);
            hookThread.setContext(getBaseContext());
            hookThread.startHookService();
            if (!hookThread.isAlive()) {
                hookThread.start();
                Log.v("WC", " 意外停止开启线程服务");
            }

            hookThread.setUncaughtExceptionHandler(uncaughtExceptionHandler);

        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        HookThread hookThread = HookThread.getIntance();
        hookThread.stopHookService();
        if (daemonthread != null && daemonthread.isAlive()) {
            isdaemonthread = false;
            daemonthread.interrupt();
        }
    }

    public boolean isRunningApp(Context context, String packageName) {
        boolean isAppRunning = false;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        for (ActivityManager.RunningTaskInfo info : list) {

            String s = info.baseActivity.getClassName();
            if (info.topActivity.getPackageName().equals(packageName) && (s.contains("LauncherUI"))) {
                isAppRunning = true;
                Log.v("WC", "已经在运行");
                break;
            } else if (info.topActivity.getPackageName().equals(packageName)) {
                break;
            }
        }
        return isAppRunning;
    }
}
